﻿namespace Harness.Recording.LocateParsers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using mshtml;

    internal class CSSLocateParseBehavior : LocateParser.ILocateParseBehavior
    {
        public string Parse(IHTMLElement element)
        {
            if (null == element)
            {
                return string.Empty;
            }

            string tag = element.tagName.ToLower();

            if (!string.IsNullOrWhiteSpace(element.id))
            {
                return string.Format("{0}#{1}", tag, element.id);
            }

            List<string> list = new List<string>();
            int eq = this.GetElementIndex(element);
            string cssClass = IE.Element.GetClassList(element).ElementAtOrDefault(0);

            if (0 != eq)
            {
                list.Add(string.Format("{0}:eq({1})", tag, eq));
            }
            else if (!string.IsNullOrWhiteSpace(cssClass))
            {
                list.Add(string.Format("{0}.{1}", tag, cssClass));
            }
            else
            {
                list.Add(string.Format("{0}", tag));
            }

            if (null != element.parentElement)
            {
                list.Add(this.Parse(element.parentElement));
            }

            list.Reverse();

            return string.Join(" > ", list);
        }

        private int GetElementIndex(IHTMLElement element)
        {
            IHTMLElement2 parentElement = element.parentElement as IHTMLElement2;

            if (null == parentElement)
            {
                return 0;
            }

            IHTMLElementCollection elementCollection = parentElement.getElementsByTagName(element.tagName);

            for (int i = 0; i < elementCollection.length; i++)
            {
                if (element == elementCollection.item(i))
                {
                    return i;
                }
            }

            return 0;
        }
    }
}
